<?php

namespace app\selladmin\model;

use think\Model;
use think\Db;

/*
 * 拓客红包
 */

class RedpacketCode extends Model {
    /*
     * 生成兑换码
     */

    public static function generateredeemcode($id) {
        $ctmLength = 5;

        $length = strlen($id);
        if ($length == $ctmLength) {
            $id = $id;
        } else if ($length < $ctmLength) {
            $lastLength = $ctmLength - $length;
            $string = '';
            for ($i = 0; $i < $lastLength; $i++) {
                $string = $string . '0';
            }
            $id = $string . $id;
        } else if ($length > $ctmLength) {
            $id = substr($id, -3);
        }

        if ($id == 85689) {
            $n = "GM";
        } elseif ($id == 85688) {
            $n = "CW";
        } else {
            $n = "KM";
        }

        $str='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $randStr = str_shuffle($str);//打乱字符串
        $rands= substr($randStr,0,4);
        $redeem_code=$n.$id.$rands;

        $exist = Db::name('redpacket_code')
                ->where('redeem_code', '=', $redeem_code)
                ->find();
        if (is_null($exist)) {
            return $redeem_code;
        } else {
            self::generateredeemcode($id);
        }
    }

}
